Leetcode 1013. Partition Array Into Three Parts With Equal Sum

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Partition Array Into Three Parts With Equal Sum

2. Solution

解析:Version 1,统计数组的和,求出三分之一是多少,如果不能整除,直接返回False,如果可以整除,计算出三分之一目标,遍历数组,因此累加数值,如果累加和等于target,则和重置为0,重新累加,记录累加和等于target的次数,如果可以满足3个以上,则返回True

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
total = sum(arr)
if total % 3 != 0:
return False
target = total // 3
count = 0
res = 0
for num in arr:
res += num
if res == target:
count += 1
res = 0
return count >=3

Reference

  1. https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/
如果有收获,可以请我喝杯咖啡!